package cz.schovjan.mte_proj.service;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import cz.schovjan.mte_proj.dto.Artist;
import cz.schovjan.mte_proj.dto.LyricResult;

public class DatabaseImpl extends SQLiteOpenHelper implements Database {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "mteprojdb";
    private static final String TABLE_ARTISTS = "artists";
    private static final String KEY_ARTIST = "artist";
    private static final String KEY_COUNT = "count";


    public DatabaseImpl(Context context) {
	super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    // vytvoreni tabulky
    @Override
    public void onCreate(SQLiteDatabase db) {
	String createTable = "CREATE TABLE " + TABLE_ARTISTS + "(" + KEY_ARTIST
		+ " TEXT PRIMARY KEY,"
		+ KEY_COUNT + " INTEGER" + ")";
	db.execSQL(createTable);
    }


    // upgrade databaze
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	// dropne tabulku pokud existuje
	db.execSQL("DROP TABLE IF EXISTS " + TABLE_ARTISTS);
	// znovu ji vytvori
	onCreate(db);
    }


    @Override
    public void addArtist(LyricResult lr) {
	// nalezeni poctu vyhledani artisty v db
	int count = countOfArtistsSearching(lr.getArtist());
	if (count == 0) {
	    // pokud se zatim nehledal, pridam ho do db
	    addArtist(lr.getArtist());
	} else {
	    // aktualizace poctu
	    updateArtist(lr.getArtist(), count + 1);
	}
    }


    /**
     * aktualizuje artistu na novy pocet vyhledavani
     * @param artist
     * @param newCount
     */
    private int updateArtist(String artist, int newCount) {
	SQLiteDatabase db = this.getWritableDatabase();
	ContentValues values = new ContentValues();
	values.put(KEY_ARTIST, artist.toLowerCase());
	values.put(KEY_COUNT, newCount);
	return db.update(TABLE_ARTISTS, values, KEY_ARTIST + " = ?", new String[] { artist.toLowerCase() });
    }


    /**
     * prida do db artistu s count = 1
     * @param artist
     */
    private void addArtist(String artist) {
	SQLiteDatabase db = this.getWritableDatabase();
	ContentValues values = new ContentValues();
	values.put(KEY_ARTIST, artist.toLowerCase());
	values.put(KEY_COUNT, 1);
	db.insert(TABLE_ARTISTS, null, values);
	db.close();
    }


    public int countOfArtistsSearching(String artist) {
	int result = 0;
	String query = "SELECT " + KEY_COUNT + " FROM " + TABLE_ARTISTS + " WHERE " + KEY_ARTIST + " = '"
		+ artist.toLowerCase() + "'";
	SQLiteDatabase db = this.getReadableDatabase();
	Cursor cursor = db.rawQuery(query, null);
	if (cursor.moveToFirst()) {
	    result = cursor.getInt(0);
	}
	cursor.close();
	return result;
    }


    public int countOfArtists() {
	int result = 0;
	String countQuery = "SELECT  * FROM " + TABLE_ARTISTS;
	SQLiteDatabase db = this.getReadableDatabase();
	Cursor cursor = db.rawQuery(countQuery, null);
	result = cursor.getCount();
	cursor.close();
	return result;
    }


    @Override
    public List<Artist> findAllArtist() {
	List<Artist> result = new ArrayList<Artist>();
	String query = "SELECT * FROM " + TABLE_ARTISTS;
	SQLiteDatabase db = this.getWritableDatabase();
	Cursor cursor = db.rawQuery(query, null);
	if (cursor.moveToFirst()) {
	    do {
		Artist a = new Artist();
		a.setArtist(cursor.getString(0));
		a.setCount(Integer.parseInt(cursor.getString(1)));
		result.add(a);
	    } while (cursor.moveToNext());
	}
	return result;
    }
}